import { HashSet } from "../Collections/HashSet";
import { ETTask } from "./ETTask";

export class ETCancellationToken {

    private actions: HashSet<Function> = new HashSet<Function>();

    public Add(callback: Function): void {
        // 如果action是null，绝对不能添加,要抛异常，说明有协程泄漏
        this.actions.Add(callback);
    }

    public Remove(callback: Function): void {
        this.actions?.Remove(callback);
    }

    public IsDispose(): boolean {
        return this.actions == null;
    }

    public Cancel(): void {
        if (this.actions == null) {
            return;
        }
        this.Invoke();
    }

    private Invoke(): void {
        let runActions = this.actions;
        this.actions = null;
        try {
            for (let key in runActions) {
                let action: Function = runActions[key];
                action.call(null);
            }
        }
        catch (e) {
            ETTask.ExceptionHandler.call(e);
        }
    }

}